<template>
  <div class="desensitization">
    <a-modal
      centered
      class="desensitization"
      width="100%"
      height="100%"
      :visible="visible"
      :maskClosable="false"
      :destroyOnClose="true"
      :title="modalTitle"
      :oktext="$t('all.autotext218')"
      @cancel="cancel"
    >
      <a-alert
        v-if="isEdit"
        class="desensitization-alert"
        :message="$t('all.autotext1280')"
        type="warning"
        closable
      />
      <div class="main">
        <div class="file-wrapper">
          <h3 class="title">{{ $t('all.autotext215') }}</h3>
          <div class="file">
            <!-- <img ref="img" :src="originalFileUrl" :alt="$t('all.autotext1324')"/> -->
            <viewer v-if="fileType === 1">
              <img :src="originalFileUrl">
            </viewer>
            <div v-if="fileType === 2" id="originalFileUrl" style="display: flex;align-items: center"></div>
          </div>
        </div>
        <div class="file-wrapper">
          <h3 class="title">{{ $t('all.autotext467') }}</h3>
          <ESign
            v-if="isEdit"
            v-bind="$attrs"
            ref="esign"
            :file-url="afterFileUrl"
            :line-color="lineColor"
            @loading="e => loading = e"
            @updateUndo="len => undoStack = len"
            @updateRedo="len => redoStack = len"
          >
          </ESign>
          <div class="file" v-else-if="afterFileUrl">
            <viewer>
              <img :src="afterFileUrl">
            </viewer>
            <!-- <img ref="img" :src="afterFileUrl" :alt="$t('all.autotext1324')"/> -->
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <template v-if="isEdit">
          <div class="tools">
            <div class="mode" :class="{active: drawMode === 'line' }" @click="useLine">
              <img src="@assets/costApply/pen.png" :title="$t('all.autotext636')" />
            </div>
            <div class="mode" :class="{active: drawMode === 'shape' }" @click="addRect">
              <img src="@assets/costApply/rectIcon.png" class="rect-icon" :title="$t('all.autotext248')"/>
            </div>
            <div class="colors">
              <div
                class="color"
                v-for="(k, i) in colors"
                :key="i"
                :class="{active: lineColor === k}"
                @click="changeColor(k)"
              >
                <div class="color-inner" :class="{white: k === '#fff'}" :style="{background: k}"></div>
              </div>
            </div>
            <div class="operator">
              <a-space size="middle">
                <a-button
                  v-if="undoStack"
                  type="primary"
                  @click="$refs.esign.undo()"
                  key="undo"
                >{{ $t('all.autotext829') }}</a-button>
                <a-button
                  v-if="redoStack"
                  type="primary"
                  @click="$refs.esign.redo()"
                  key="redo"
                >{{ $t('all.autotext1028') }}</a-button>
              </a-space>
            </div>
            <div class="desense-confirm-checkbox">
              <a-checkbox v-model="desenseChecked" :disabled="loading">{{ $t('all.autotext665') }}</a-checkbox>
            </div>
          </div>
          <div class="footer__btn">
            <a-space size="middle">
              <a-button @click="$refs.esign.reset()">{{ $t('all.autotext1312') }}</a-button>
              <a-button
                :disabled="loading"
                @click="handleGenerate"
                type="primary"
                :loading="generateLoading"
              >{{ $t('all.autotext417') }}
              </a-button>
            </a-space>
          </div>
        </template>
      </span>
    </a-modal>
  </div>
</template>

<script>
import ESign from '@comp/ESign/index.vue'
import { FILE_TYPE } from '@/constants/common'
import { dataURLtoBlob } from '@/utils/util'
import { uploadFile } from '@api/common'
import Pdfh5 from 'pdfh5'
import 'pdfh5/css/pdfh5.css'

export default {
  name: 'desensitization-modal',
  components: {
    ESign
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'edit'
    },
    fileType: {
      type: Number,
      default: FILE_TYPE.IMAGE.value
    },
    // 原始上传文件url
    originalFileUrl: {
      type: String,
      default: ''
    },
    // 脱敏后图片 url
    afterFileUrl: {
      type: String,
      default: ''
    },
    fileName: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      drawMode: 'line',
      redoStack: 0,
      undoStack: 0,
      colors: ['#A5AFBD', '#F64C4C', '#3A70E2', '#0C9D61', '#FFAA29', '#031F47', '#fff', '#000'],
      lineColor: '#031F47',
      desenseChecked: false, // 确认脱敏完成，确认后才可以进行更新图片
      generateLoading: false,
      loading: true,
      numPages: 1,
      originalPdfFileUrl: ''
    }
  },
  computed: {
    isEdit () {
      return this.type === 'edit'
    },
    modalTitle () {
      return this.isEdit ? this.$t('all.autotext920') : this.$t('all.autotext1421')
    }
  },
  methods: {
    init () {
      this.$refs.esign && this.$refs.esign.initImg()
      /* eslint-disable no-new */
      new Pdfh5('#originalFileUrl', {
        pdfurl: this.originalFileUrl,
        lazy: true,
        cMapUrl: 'https://unpkg.com/pdfjs-dist@3.8.162/cmaps/'
        // responseType: "blob" 
      })
    },
    resetData () {
      Object.keys(this.$data).forEach(key => {
        this.$data[key] = this.$options.data.call(this)[key]
      })
    },
    cancel () {
      this.$emit('cancel')
      this.resetData()
    },
    useLine () {
      this.drawMode = 'line'
      this.$refs.esign.useLine()
    },
    addRect () {
      this.drawMode = 'shape'
      this.$refs.esign.drawShape()
    },
    changeColor (color) {
      this.lineColor = color
      this.$refs.esign.updateDrawSettings(color)
    },
    // 生成图
    handleGenerate () {
      if (!this.desenseChecked) {
        return this.$message.warning(this.$t('all.autotext708'))
      }
      this.generateLoading = true
      const res = this.$refs.esign.generate()
      const blob = dataURLtoBlob(res)
      const fileName = this.pdfFileNameToPng(this.fileName)
      const file = new File([blob], fileName)
      this.updateImg(file)
    },
    pdfFileNameToPng (fileName) {
      return fileName.replace(/.(pdf|PDF)$/, '.png')
    },
    // 上传图片
    updateImg (imageFile) {
      const params = new FormData()
      params.append('file', imageFile)
      uploadFile(params).then(res => {
        this.$message.success(this.$t('all.autotext1250'))
        this.$emit('ok', res)
        this.cancel()
      }).finally(() => {
        this.generateLoading = false
      })
    }
  }
}
</script>

<style scoped lang='less'>
.desensitization {
  /deep/ .ant-modal {
    padding: 0;
    .ant-modal-content {
      height: 100%;
    }
    .ant-modal-body {
      padding: 0;
      height: calc(100% - 55px - 120px);
      overflow-y: auto;
      .desensitization-alert {
        .ant-alert-message {
          color: #F02F2F;
        }
      }
      .main {
        height: 100%;
        display: flex;
        .file-wrapper {
          flex-basis: 50%;
          position: relative;
          padding: 40px;
          .file {
            height: 100%;
            overflow-y: auto;
            div{
              > img {
                max-width: 100%;
              }
            }

          }
        }
      }
    }
    .ant-modal-footer {
      height: 120px;
      .tools {
        height: 50px;
        display: flex;
        column-gap: 40px;
        justify-content: center;
        align-items: center;
        .mode {
          cursor: pointer;
        }
        .colors {
          display: flex;
          align-items: center;
          .color {
            width: 24px;
            height: 24px;
            cursor: pointer;
            border-radius: 50%;
            margin-right: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            &.active {
              border: 1px solid #031F47;
            }
            .color-inner {
              border-radius: 50%;
              width: 18px;
              height: 18px;
              &.white {
                border: 1px solid #031F47;
              }
            }
          }
        }
        .operator {
          width: 180px;
          text-align: left;
        }
      }
      .footer__btn {
        text-align: center;
      }
    }
  }
}
</style>
